package NIO;

import com.sun.security.ntlm.Server;

import javax.print.DocFlavor;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.SocketAddress;
import java.net.SocketOption;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.Set;

public class WriteServer {
    public static void main(String[] args) throws IOException {
        ServerSocketChannel ssc=ServerSocketChannel.open();
        ssc.configureBlocking(false);
        ssc.bind(new InetSocketAddress(8080));

        Selector selector=Selector.open();
        ssc.register(selector, SelectionKey.OP_ACCEPT,null);
        int count=0;

        while (true){
            selector.select();

            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()){
                SelectionKey next = iterator.next();
                iterator.remove();
                if (next.isAcceptable()){
                    SocketChannel accept = ssc.accept();
                    accept.configureBlocking(false);
                    SelectionKey register = accept.register(selector, SelectionKey.OP_READ);
                    //向客户端发送
                    StringBuilder sb=new StringBuilder();
                    for (int i=0;i<3000000;i++){
                        sb.append("a");
                    }
                    ByteBuffer byteBuffer= Charset.defaultCharset().encode(sb.toString());
                    int write = accept.write(byteBuffer);//返回的是实际写入的字节数量
                    System.out.println("实际写入："+write);

                    //当还有剩余的时候，需要添加关注写事件
                    if (byteBuffer.hasRemaining()){
                        //在原有事件上，关注写事件
                        register.interestOps(register.interestOps()+SelectionKey.OP_WRITE);

                        //把byteBuffer通过附件与该channel关联
                        register.attach(byteBuffer);
                    }
                }else if (next.isWritable()){
                    ByteBuffer attach =(ByteBuffer) next.attachment();
                    SocketChannel sc=(SocketChannel) next.channel();
                    int write = sc.write(attach);
                    System.out.println("实际写入："+write);

                    //代表写完了
                    if (!attach.hasRemaining()){
                        next.interestOps(next.interestOps()-SelectionKey.OP_WRITE);
                        next.attach(null);
                    }
                }
            }

        }
    }
}
